import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {RoomManageService} from './room-manage.service';
import {FloorManageService} from './floor-manage.service';
import {Response} from '../../../core/domain/response';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {Floor} from './floor';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Room} from './room';
import {CopyUtil} from '../../../utils/copy.util';
import {StatusEnum} from '../../../core/enum/status.enum';
import {TeacherService} from '../teacher/teacher.service';
import {OtherUtil} from '../../../utils/other.util';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {StorageUtil} from '../../../utils/storage.util';
import {SourceServer} from '../../../common/source.server';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {FilterEnum} from '../../../core/enum/filter.enum';

declare var $: any;

@Component({
    selector: 'app-room-manage',
    templateUrl: './room-manage.component.html',
    styleUrls: ['./room-manage.component.scss'],
    providers: [RoomManageService, FloorManageService, TeacherService, SourceServer]
})
export class RoomManageComponent implements OnInit {
    // 分页查询条件
    selectXqhId = null;
    buildingId = null;
    floorId = null;
    roomNumber = null;
    roomName = null;
    pageInfo: PageEntity = new PageEntity();
    selectAddTree = []; // 点击新增时候默认的楼层选择

    // 页面状态是否转变
    isIndeterminate = false;
    // 数据key与选中状态
    mapOfCheckedId: { [key: string]: boolean } = {};

    // 楼栋楼层
    buildFloor: Floor = new Floor();
    // 房间列表
    list: any[] = [];
    displayList = [];
    // 房间
    room: Room = new Room();
    // 选择树
    treeNodes: any[] = [];
    // 下拉选择树
    treeNodesDatas: any[] = [];

    // 是否打开书编辑框
    isFloor = false;
    isRoom = false;
    isAllCheck = false;
    // 楼栋楼层树配置
    setting = {
        data: {
            key: {
                name: 'title'
            },
            simpleData: {
                enable: true,
                idKey: 'key'
            },
            keep: {
                parent: true,
                leaf: true
            }
        },
        // edit: {
        //   enable: true,
        //   showRemoveBtn: false,
        //   showRenameBtn: false
        // },
        // 树点击事件
        callback: {
            onClick: (event, treeId, treeNode) => {
                this.roomNumber = null;
                this.roomName = null;
                this.selectXqhId = null;
                this.buildingId = null;
                this.floorId = null;
                this.pageInfo.filters = {};
                if (treeNode.level === 1) {
                  this.pageInfo.filters['xqhId'.toString()] = PaginationUtils.filters(treeNode.key, FilterEnum.CONTAINS);
                  this.selectXqhId = treeNode.key;
                } else if (treeNode.level === 2) {
                  this.pageInfo.filters['buildingId'.toString()] = PaginationUtils.filters(treeNode.key, FilterEnum.CONTAINS);
                  this.buildingId = treeNode.key;
                } else if (treeNode.level === 3) {
                  this.pageInfo.filters['floorId'.toString()] = PaginationUtils.filters(treeNode.key, FilterEnum.CONTAINS);
                  this.floorId = treeNode.key;
                }

                this.selectAddTree = [];
                const temp = [];
                let node = treeNode.getParentNode();
                while (node) {
                  temp.push(node);
                  node = node.getParentNode();
                }
                temp.forEach(tm => {
                  if (tm.level !== 0 ) {
                    this.selectAddTree.unshift(tm.key);
                  }
                });
                this.selectAddTree.push(treeNode.key);


                this.pageInfo.first = 1;
                this.page();
            },
            onRename: (event, treeId, treeNode) => {
                this.roomNumber = null;
                this.roomName = null;
                this.flootServe.update({
                    id: treeNode.key,
                    name: treeNode.title,
                    parentId: treeNode.parentId,
                    type: treeNode.type
                }).subscribe(res => {
                    const {status, message} = res;
                    if (status === StatusEnum.SUCCESS) {
                        this.message.success(message);
                    }
                });
            }
        },
        view: {
            showIcon: false,
            addHoverDom: (treeId, treeNode) => {
                if (treeNode.key === 'floor_root') { return; }
                const aObj = $('#' + treeNode.tId + '_a');
                if ($('#' + treeNode.id + '_edit').length > 0) {
                    return;
                }
                if (this.showBtns !== 1) { return; }
                let editStr = '<span class="button edit" id="' + treeNode.id + '_edit" title="重命名"></span>'
                    + '<span class="button remove" id="' + treeNode.id + '_remove" title="删除"></span>';
                if (treeNode.level < 3) {
                  editStr += '<span class="button add" id="' + treeNode.id + '_add" title="新增"></span>';
                }
                aObj.append(editStr);
                const edit = $('#' + treeNode.id + '_edit');
                const remove = $('#' + treeNode.id + '_remove');
                const add = $('#' + treeNode.id + '_add');
                const zTree = $.fn.zTree.getZTreeObj(treeId);
                if (edit) {
                    edit.bind('click', () => {
                        if (treeNode) {
                            zTree.editName(treeNode);
                        }
                    });
                }
                if (add) {
                    add.bind('click', () => {
                        treeNode.isParent = true;
                        this.isFloor = true;
                        this.buildFloor.parentId = treeNode.key;
                        this.buildFloor.type = treeNode.level;
                        this.buildFloor.name = '';
                        this.initBuildFloorForm();
                    });
                }
                if (remove) {
                    remove.bind('click', () => {
                        this.flootServe.delete(treeNode.key).subscribe(res => {
                            this.message.success(res.message);
                            this.setTree();
                            this.getTreeDatas();
                        });
                    });
                }
            },
            removeHoverDom: (treeId, treeNode) => {
                $('#' + treeNode.id + '_edit').remove();
                $('#' + treeNode.id + '_remove').remove();
                $('#' + treeNode.id + '_add').remove();
            }
        }
    };
    // 楼栋楼层表单
    buildFloorForm: FormGroup;
    roomForm: FormGroup;
    buildFloorIds = [];
    roomTypeList: RoomType[] = [];
    // 负责人列表
    chargePerson = [];
    canDelete = true;

    uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;

    headerInfo = null;
    previewImage: string | undefined = '';
    previewVisible = false;
    showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        hidePreviewIconInNonImage: true
    };
    fileList: UploadFile[] = [];
    fileListImport: UploadFile[] = [];
    isEdit = false;

    linkModal = false; // 关联弹框
    linkForm: FormGroup;
    linkRoomVal = [];
    jwList = [];
    currRoomId = null;

    showBtns = 1; // 当前登录人是否有操作权限,0-隐藏 1-显示
    xqhId = '';
    constructor(private roomServe: RoomManageService,
                private flootServe: FloorManageService,
                private message: NzMessageService,
                private sourceServe: SourceServer,
                private formBuilder: FormBuilder,
                private teacherServer: TeacherService) {
    }

    ngOnInit() {
        this.headerInfo = StorageUtil.getFileHeader();
        // this.showBtns = StorageUtil.getLocalStorage('roleManager');
        // 初始化树
        this.setTree();
        // 初始化楼栋楼层表单
        this.initBuildFloorForm();
        // 初始化房间表单
        this.initRoomForm();
        this.initLinkForm(); // 初始化关联表单
        // 初始化房间页面
        this.pageList();
        // 获取树结构数据--用于新增编辑
        this.getTreeDatas();
        // 房间类型
        this.roomServe.roomTypeList().subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.roomTypeList = datas;
            }
        });
        this.getJwListData(); // 查询关联的场地
    }

    checkDelete(): void {
        this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
    }

    /**
     * 初始化表单对象
     */
    initBuildFloorForm() {
        this.buildFloorForm = this.formBuilder.group({
            name: [null, [Validators.required]]
        });
    }

    /**
     * 初始化表单对象
     */
    initRoomForm() {
        this.roomForm = this.formBuilder.group({
            buildFloorIds: [null, [Validators.required]],
            name: [null, [Validators.required]],
            number: [null, [Validators.required]],
            remark: [null, []],
            areas: [null, [Validators.required]],
            type: [null, [Validators.required]],
            inChargePersonId: [null, [Validators.required]],
            modelNumber: [null, []],
            mxId: [null, []]
        });
    }

  /**
   * 初始化表单对象
   */
  initLinkForm() {
    this.linkForm = this.formBuilder.group({
      linkRoomId: [null, [Validators.required]]
    });
  }

    /**
     * 处理树节点
     */
    setTree() {
        this.flootServe.treeAll().subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.treeNodes = datas;
                $.fn.zTree.init($('#treeText'), this.setting, datas);
                const functionLimitList = $.fn.zTree.getZTreeObj('treeText');
                functionLimitList.expandAll(true);
                // 初始化显示第一个数据节点数据
                // 获取第一个节点
                const node = functionLimitList.getNodes()[0];
                functionLimitList.selectNode(node);
                functionLimitList.setting.callback.onClick(null, functionLimitList.setting.treeId, node);
            }
        });
    }

    /**
     * 楼层发生改变时
     */
      changeBuildFloor(value) {
        this.xqhId = value[0];
      }

  /**
   * 新增修改获取树节点数据
   */
  getTreeDatas() {
    this.flootServe.tree().subscribe((res: Response) => {
      const {datas, status} = res;
      if (status === StatusEnum.SUCCESS) {
        this.treeNodesDatas = datas;
      }
    });
  }

    /**
     * 添加楼层或者楼栋
     */
    addBuild(): void {
        this.buildFloor = new Floor();
        this.buildFloor.type = 0;
        this.buildFloor.parentId = '';
        this.isFloor = true;
    }

    /**
     * 新增楼层楼栋
     */
    submitBuildFloor() {
        this.flootServe.create(this.buildFloor).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.isFloor = false;
                this.setTree();
                this.getTreeDatas();
                this.message.success(message);
            }
        });
    }

    reset(): void {
        this.roomNumber = null;
        this.roomName = null;
        this.pageInfo.first = 1;
        this.pageInfo.filters['number'.toString()] = undefined;
        this.pageInfo.filters['name'.toString()] = undefined;
        this.page();

    }

    /**
     * 请求页面数据
     */
    pageList() {
        this.pageInfo.first = 1;
        this.roomServe.pageFarm(this.pageInfo, [
            {name: 'name', value: this.roomName},
            {name: 'number', value: this.roomNumber},
            {name: 'xqhId', value: this.selectXqhId},
            {name: 'buildingId', value: this.buildingId},
            {name: 'floorId', value: this.floorId}
        ]);
        this.page();
    }

    page(): void {
        this.roomServe.page(this.pageInfo).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                const {data, totalRecords} = datas;
                this.list = data;
                this.pageInfo.totalRecords = totalRecords;
            }
        });
    }

    /**
     * 页面全选
     * @param event 全选状态
     */
    checkAll(event: boolean): void {
        this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = event));
        this.refreshStatus();
    }

    /**
     * 置换页面各数据选中状态
     */
    refreshStatus(): void {
        this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
        this.isIndeterminate =
            this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
            !this.isAllCheck;
        this.checkDelete();
    }

    /**
     * 页面数据转化时触发
     * @param event 是否转变
     */
    currentPageDataChange(event): void {
        this.displayList = event;
        this.refreshStatus();
    }

    /**
     * 初始化负责人
     */
    initChargePerson(): void {
        if (this.chargePerson.length) {
            return;
        }
        this.teacherServer.list().subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.chargePerson = res.datas;
            }
        });
    }

    addRoom() {
        // 初始化负责人
        this.initChargePerson();
        this.initRoomForm();
        // this.setTree();
        if (this.selectAddTree.length >= 3) {
          this.buildFloorIds = this.selectAddTree;
        } else {
          this.buildFloorIds = [];
        }
        this.fileList = [];
        this.room = new Room();
        this.isRoom = true;
    }

    /*关联*/
    linkRoom(data) {
      this.currRoomId = data.id;
      this.linkRoomVal = [];
      this.initLinkForm();
      this.roomServe.findSelectedList({id: data.id}).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.linkRoomVal = res.datas.cdIdList;
          this.linkModal = true;
        }
      });
    }

    /*查询场地*/
  getJwListData() {
    this.roomServe.getJwList().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.jwList = res.datas;
      }
    });
  }

    // 保存关联
  submitLink() {
      const obj = {
        cdIdList: this.linkRoomVal,
        roomId: this.currRoomId
      };
      this.roomServe.saveJwList(obj).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.message.success(res.message);
          this.linkModal = false;
        }
      });
  }

    /**
     * 编辑房间信息
     * @param item 房间信息
     */
    editRoom(item: Room): void {
        this.room = new Room();
        const te = [];
        this.initChargePerson();
        this.room = CopyUtil.deepCopy(item, {});
        if (this.room != null && this.room.iconVO) {
            const test = {
                uid: this.room.iconVO.id,
                name: this.room.iconVO.fileOriginalName,
                status: 'done',
                url: HTTP_BASE_URL + SERVERS_NAME.IMAGE_URL + this.room.iconVO.moduleName + '/' + this.room.iconVO.fileNewName
            };
            te.push(test);
        }
        this.fileList = [...te];
        this.buildFloorIds = [item.xqhId, item.buildingId, item.floorId];
        this.isRoom = true;
    }

    /**
     * 提交房间编辑信息
     */
    submitRoom() {
        let postName = 'create';
        if (this.room.id) {
            postName = 'update';
            this.roomForm.value['id'.toString()] = this.room.id;
        }
        // 补充房间图片
        if (this.fileList.length > 0) {
            this.roomForm.value['icon'.toString()] = this.fileList[0].uid;
        }
        this.roomForm.value['buildingId'.toString()] = this.buildFloorIds[1];
        if (this.buildFloorIds.length < 3) {
          this.message.error('请选择到第三级!');
          return false;
        }
        this.roomForm.value['floorId'.toString()] = this.buildFloorIds[2];
        this.roomServe[postName]({...this.roomForm.value, xqhId: this.xqhId}).subscribe((res: Response) => {
            const {status} = res;
            if (status === StatusEnum.SUCCESS) {
                this.buildFloorIds = [];
                this.pageList();
                this.isRoom = false;
            }
        });
    }

    /**
     * 删除所有
     */
    deleteAll() {
        const arr = [];
        for (const val in this.mapOfCheckedId) {
            if (this.mapOfCheckedId[val]) {
                arr[arr.length] = val;
            }
        }
        if (arr.length < 1) {
            this.message.warning('请勾选要删除的数据!');
            return;
        }
        this.roomServe.deleteAll(arr).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
                this.mapOfCheckedId = {};
                this.pageInfo.first = 1;
                this.pageList();
            }
        });
    }

    cancelFn(): void {
        this.canDelete = true;
        this.isAllCheck = false;
        this.mapOfCheckedId = {};
        this.isIndeterminate = false;
    }

    /**
     * 删除房间
     */
    deleteRoom(roomId: string): void {
        this.roomServe.deleteAll([roomId]).subscribe((res: Response) => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
                this.pageList();
            }

        });
    }


    /**
     * 删除上传资源
     * @param file s
     */
    deleteFlile = (file: UploadFile) => {
        if (this.isEdit) {
            $('.ant-upload-list-item').find('nz-icon').css('display', 'none');
            return false;
        } else {
            $('.ant-upload-list-item').find('nz-icon').css('display', '');
        }
        const temList = [];
        this.fileList.forEach((item) => {
            if (item.uid === file.uid) {
                this.sourceServe.deleteFile([item.uid]).subscribe(res => {
                    if (res.status === StatusEnum.SUCCESS) {
                        this.message.success('文件删除成功!');
                    }
                });
            } else {
                temList.push(item);
            }
        });
        this.fileList = temList;
    };

    /**
     * 附件上传回调
     * @param event 上传回调信息
     */
    getUploadInfo(event) {
        const {file, fileList, type} = event;
        if (type === 'success') {
            if (file.response.status === StatusEnum.SUCCESS) {
                fileList.forEach((item) => {
                    if (item.response) {
                        const datas = item.response.datas;
                        item.uid = datas.id;
                        item.url = HTTP_BASE_URL + SERVERS_NAME.IMAGE_URL + datas.moduleName + '/' + datas.fileNewName;
                    }
                });
                this.fileList = fileList;
            } else {
                this.message.warning('文件上传失败,请移除文件!');
            }
        }
    }

    handlePreview = (file: UploadFile) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
    };
}

export class RoomType {
    keyValue?: string;
    keyCode?: string;
}
